package com.laoxu.demo.bootstrapcurd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.laoxu.demo.bootstrapcurd.common.Result;
import com.laoxu.demo.bootstrapcurd.common.ResultUtil;
import com.laoxu.demo.bootstrapcurd.model.EmqUser;
import com.laoxu.demo.bootstrapcurd.service.EmqUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


@RequestMapping("/emqUser")
@Controller
public class EmqUserController {

    @Autowired
    private EmqUserService emqUserService;

    @RequestMapping
    public String user(){
        return "mqtt_user";
    }

    @GetMapping("/{id}")
    @ResponseBody
    public Result<EmqUser> get(@PathVariable Integer id){
        EmqUser user =  emqUserService.getById(id);
        return ResultUtil.ok(user);
    }


    @PostMapping("/list")
    @ResponseBody
    public Result<IPage<EmqUser>> list(@RequestParam(value = "username", required = false) String username,
                                       @RequestParam(defaultValue = "1") Integer pageNo,
                                       @RequestParam(defaultValue = "10") Integer pageSize){
        // 构造查询条件
        QueryWrapper<EmqUser> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(username)){
            queryWrapper.like("username",username);
            queryWrapper.orderByDesc("created");
        }
        Page<EmqUser> page = new Page<>(pageNo,pageSize);

        IPage<EmqUser> result = emqUserService.page(page, queryWrapper);
        // 设置总记录数
        result.setTotal(emqUserService.count(queryWrapper));

        return ResultUtil.ok(result);
    }


    @PostMapping("/add")
    @ResponseBody
    public Result<String> add(@RequestBody EmqUser user){
        emqUserService.save(user);
        return ResultUtil.ok("添加成功！");
    }


    @PostMapping("/modify")
    @ResponseBody
    public Result<String> modify(@RequestBody EmqUser user){
        emqUserService.saveOrUpdate(user);
        return ResultUtil.ok("修改成功！");
    }



    @PostMapping("/remove")
    @ResponseBody
    public Result<String> remove(@RequestParam Integer id){
        emqUserService.removeById(id);
        return ResultUtil.ok("删除成功！");
    }





}
